package com.pine.common.threadpool;

import lombok.NonNull;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Daemon线程工厂
 *
 * @author pine manage
 * @since 2024-08-28
 */
public class DaemonThreadFactory implements java.util.concurrent.ThreadFactory {
    private static final AtomicInteger THREAD_POOL_NUMBER = new AtomicInteger(1);
    private final AtomicInteger THREAD_NUMBER = new AtomicInteger(1);

    private final ThreadGroup threadGroup;
    private final String threadNamePrefix;

    public DaemonThreadFactory(String threadPoolName) {
        threadGroup = Thread.currentThread().getThreadGroup();
        this.threadNamePrefix = threadPoolName + "-" + THREAD_POOL_NUMBER.getAndIncrement() + "-thread-";
    }

    @Override
    public Thread newThread(@NonNull Runnable runnable) {
        Thread thread = new Thread(this.threadGroup, runnable, this.threadNamePrefix + this.THREAD_NUMBER.getAndIncrement(), 0L);
        thread.setDaemon(true);
        return thread;
    }
}
